package org.irri.smta.service.impl;

import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.irri.smta.domain.Role;
import org.irri.smta.repository.IRoleRepository;
import org.irri.smta.service.IRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

@Named("roleService")
@Transactional(readOnly = true)
public class RoleService implements IRoleService<Role, Long> {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(RoleService.class);

	@Inject
	@Named("roleRepository")
	private IRoleRepository roleRepository;
	
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	@Override
	public Role create(Role role) {
		LOGGER.debug("Role create(Role role):" + role);
		Date now = new Date();
		role.setCreatedDate(now);
		role.setUpdatedDate(now);
		LOGGER.debug("Creating a new role with information: " + role);
		return roleRepository.save(role);
	}

	@Transactional(readOnly = false, rollbackFor = Exception.class)
	@Override
	public Role update(Role role) throws Exception {
		LOGGER.debug("Role update(Role role): " + role);
		role.setUpdatedDate(new Date());
		LOGGER.debug("Updating role with information: " + role);

		Role roleDb = roleRepository.findOne(role.getId());

		if (roleDb == null) {
			LOGGER.debug("No role found with id: " + role.getId());
			throw new Exception();
		}

		roleRepository.save(role);
		return role;
	}

	@Transactional(readOnly = false, rollbackFor = Exception.class)
	@Override
	public Role delete(Long id) throws Exception {
		LOGGER.debug("Role delete(Long id): " + id);

		Role role = roleRepository.findOne(id);

		if (role == null) {
			LOGGER.debug("No role found with id: " + id);
			throw new Exception();
		}

		roleRepository.delete(role);
		return role;
	}

	@Transactional(readOnly = true)
	@Override
	public Role findById(Long id) {
		LOGGER.debug("Role findById(Long id): " + id);
		return roleRepository.findOne(id);
	}

	@Transactional(readOnly = true)
	@Override
	public Role getDefaultRole() {
		LOGGER.debug("Role getDefaultRole()");
		return roleRepository.findOne(Role.DEFAULT_ROLE_ID);
	}

	@Transactional(readOnly = true)
	@Override
	public List<Role> findAll() {
		LOGGER.debug("List<Role> findAll()");
		return roleRepository.findAll();
	}

	@Transactional(readOnly = true)
	@Override
	public List<Role> findAllOrdered() {
		LOGGER.debug("List<Role> findAllOrdered()");
		return roleRepository.findAllOrdered();
	}

}
